const path = require('path');
const glob = require('glob');
const {
    CleanWebpackPlugin
} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

// 设置多入口函数
const _setWebpackEntry = (entries, entryNames) => {
    const res = {}; // 初始化返回结果
    // 设置路径内容
    for (let i = 0; i < entryNames.length; i++) {
        res[entryNames[i]] = entries[i];
    }
    // console.dir(res);
    return res;
};

// 设置html插件函数
const _setHtmlWebpackPlugins = (templateUrls, chunks) => {
    const htmlPlugins = []; // html插件列表
    templateUrls.forEach((url, index) => {
        htmlPlugins.push(new HtmlWebpackPlugin({
            template: url,
            filename:`${chunks[index]}.html`,// 一定要设置，默认的index.html会覆盖所有设置
            excludeChunks: ["node_modules"],
            chunks: [`${chunks[index]}`],// 重要！判断输出的html与哪个入口chunk对应
            title: chunks[index]
        }))
    });
    return htmlPlugins;
};

// 自动设置webpack参数
const autoSetWebpackParams = () => {
    const entryList = glob.sync(path.join(__dirname, "pages/*/*.js")); // 获得入口文件列表路径
    const chunkNames = entryList.map((entry) => entry.match(/[^\/]\w+\.js$/)[0]
        .replace(/\.js/, "")); // 拿到入口名称，重要，涉及到chunk名
    const entries = _setWebpackEntry(entryList, chunkNames); // 拿到入口对象
    const templates = glob.sync(path.join(__dirname, "pages/*/*.html"));; // 获得html文件列表
    const htmlPlugins = _setHtmlWebpackPlugins(templates, chunkNames);
    return {
        entries,
        htmlPlugins
    };
}

const {
    entries,
    htmlPlugins
} = autoSetWebpackParams(); // 解构取出参数

module.exports = {
    entry: entries,
    output: {
        filename: '[name]_[chunkhash:4].js', // 文件指纹
        path: path.join(__dirname, 'dist')
    },
    plugins: [
        ...htmlPlugins,
        new CleanWebpackPlugin(),
    ],
    mode: 'production',
};